<template>
  <div class="expense-container">
    <van-nav-bar title="报销申请" fixed placeholder left-arrow @click="handleBack" />
    <!-- 申请表单 -->
    <van-form class="form-card" @submit="handleExpenseSubmit">
      <van-cell-group inset>
        <!-- 报销事由 -->
        <van-field
          v-model="form.subject"
          name="subject"
          label="报销主题"
          type="textarea"
          placeholder="请输入报销主题..."
          autosize
          required
        />
        <!-- 报销类型 -->
        <van-field
          v-model="displayExpenseType"
          name="expenseType"
          label="*报销类型"
          placeholder="请选择类型"
          is-link
          readonly
          required
          @click="showExpenseTypePicker = true"
        />
        <!-- 报销金额 -->
        <van-field
          v-model="form.amount"
          name="amount"
          label="*报销金额"
          placeholder="请输入金额"
          type="number"
          required
        />
        <!-- 文件上传 -->
        <van-field name="applicationMaterials" label="文件上传">
          <template #input>
            <van-uploader v-model="magesFiles.values[0]" :maxCount="1" :after-read="handleAfterRead" @click="console.log('点击选择文件')" accept="image/*"/>
          </template>
        </van-field>
      </van-cell-group>

      <!-- 提交按钮 -->
      <div class="submit-btn">
        <van-button
          round
          block
          type="primary"
          native-type="submit"
          :loading="submittingExpense"
        >
          提交申请
        </van-button>
      </div>
    </van-form>

    <!-- 历史记录 -->
    <div class="history-card">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多记录"
        @load="loadExpenseHistory"
      >
      <van-cell
        v-for="(item, index) in expenseHistoryList"
        :key="index"
        :title="`${getExpenseTypeName(item.expenseType)} | 金额：￥${item.amount}`"
        :value="item.reason"
      >
 
        <span class="create-time">{{ item.submitTime }}</span>
        
        <template #label>
          <!-- <div class="reason-label">{{ item.reason }}</div> -->
          <div class="time-info">
              <span>报销主题:  {{ item.subject }}</span>
            </div>
            <van-tag 
              :type="statusTagMap[item.status]" 
              size="medium"
              class="status-tag"
            >
              {{ statusTextMap[item.status] }}
                  <!-- 新增的备注信息 -->
            </van-tag>
            <span v-if="(item.status === 1 || item.status === 2) && item.remark" class="approve-comment">备注：{{ item.remark }}</span>
            <van-button class="cancelExpense" v-if="item.status === 0" type="danger" size="small" @click="cancelExpense(item.id)">撤销申请</van-button>
          </template>

        <!-- <div class="remark-info">
              <span>报销主题:{{ item.subject }}</span>
            </div>
        <van-tag 
        :type="statusTagMap[item.status]" 
        size="medium"
        class="status-tag"
        >

          {{ statusTextMap[item.status] }} -->
        <!-- 新增的备注信息 -->
        <!-- </van-tag>
        <span v-if="(item.status === 1 || item.status === 2) && item.remark" class="approve-comment">备注：{{ item.remark }}</span>
        <van-button class="cancelLeave" v-if="item.status === 0" type="danger" size="small" @click="cancelLeave(item.id)">撤销申请
        </van-button> -->
      </van-cell>
      </van-list>
    </div>

    <!-- 报销类型选择器 -->
    <van-popup v-model:show="showExpenseTypePicker" position="bottom">
      <van-picker
        :columns="expenseTypeOptions"
        @confirm="onExpenseTypeConfirm"
        @cancel="showExpenseTypePicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import moment from'moment';
import { showToast } from 'vant';
import {
  submitExpenseService,
  getExpenseHistoryService,
  cancelExpenseService,
  uploadFileService
} from '@/api/expense';

// 表单数据
const form = ref({
  expenseType: null,
  amount: '',
  applyDocuments: '',
  subject: '',
  submitTime: '',
});

// 存储上传的文件
const magesFiles = ref([]);

// 历史记录
const expenseHistoryList = ref([]);
const loading = ref(false);
const finished = ref(false);
const currentPage = ref(1);

// 状态映射
const statusTextMap = ['待审批', '已通过', '已拒绝', '已撤销'];
const statusTagMap = ['primary','success', 'danger', 'warning'];

// 报销类型选项
const expenseTypeOptions = ref([
  { text: '交通费', value: 0 },
  { text: '差旅费', value: 1 },
  { text: '办公用品', value: 2 },
  { text: '业务招待', value: 3 }
]);

// 获取报销类型文字
const getExpenseTypeName = (type) => {
  const option = expenseTypeOptions.value.find(option => option.value === type);
  return option? option.text : '未知类型';
};

const displayExpenseType = computed({
  get: () => expenseTypeOptions.value.find(o => o.value === form.value.expenseType)?.text || '',
  set: () => {}
});
const onTypeConfirm = ({ selectedOptions }) => {
  form.value.leaveType = selectedOptions[0]?.value ?? ''
  showTypePicker.value = false
}
const showExpenseTypePicker = ref(false);
const submittingExpense = ref(false);

// 处理文件读取后的操作
const handleAfterRead = async (file) => {
  const formData = new FormData();
  formData.append('file', file.file);
  const response = await uploadFileService(formData);
  console.log('上传成功');
  // 假设response.data是图片URL
  if (typeof response.data ==='string') {
    magesFiles.value = [{ url: response.data }];
  } else {
    magesFiles.value = response.data;
  }
  console.log(magesFiles.value[0].url);
  form.value.applyDocuments = magesFiles.value[0].url;
};

// 表单提交
const handleExpenseSubmit = async () => {
  console.log(form.value);
  const submitData = {
   ...form.value,
    submitTime:  moment().format('YYYY-MM-DD HH:mm:ss'),
    expenseType: Number(form.value.expenseType)
    
  };

  if (!validateExpenseForm()) return;

  submittingExpense.value = true;

  const result = await submitExpenseService(submitData);
  showToast(result.description || '提交成功');
  submittingExpense.value = false;
  loadExpenseHistory(true);
};

// 表单验证
const validateExpenseForm = () => {
  if (form.value.expenseType === null || form.value.expenseType === undefined) {
    showToast('请选择报销类型');
    return false;
  }
  if (form.value.amount === '') {
    showToast('请输入报销金额');
    return false;
  }

  if (!form.value.subject.trim()) {
    showToast('请填写报销事由');
    return false;
  }
  return true;
};

// 加载历史记录
const loadExpenseHistory = async (reset = false) => {
  if (reset) {
    currentPage.value = 1;
    expenseHistoryList.value = [];
    finished.value = false;
  }
  if (finished.value) return;
  loading.value = true;
  try {
    const res = await getExpenseHistoryService(currentPage.value);
    if (res.data.records && res.data.records.length > 0) {
      const sortedRecords = res.data.records.slice().reverse();
      expenseHistoryList.value = reset? sortedRecords : [...sortedRecords, ...expenseHistoryList.value];
      currentPage.value++;
      // 这里根据实际情况判断是否还有更多数据，假设每页固定返回5条数据
      finished.value = res.data.records.length < 5;
    } else {
      finished.value = true;
    }
  } catch (error) {
    console.error('加载历史记录出错:', error);
  } finally {
    loading.value = false;
  }

};

// 撤销报销申请
const cancelExpense = async (expenseId) => {
  const result = await cancelExpenseService(expenseId);
  showToast('撤销成功');
  loadExpenseHistory(true);
};

import { useRouter } from 'vue-router';
const router = useRouter();
const handleBack = () => {
  router.push('/workbenches');
  console.log('返回上一页');
};

const onExpenseTypeConfirm = ({ selectedOptions }) => {
  form.value.expenseType = selectedOptions[0]?.value ?? ''
  showExpenseTypePicker.value = false;
};
</script>

<style scoped>
.expense-container {
  background: #f8f8f8;
  min-height: 100vh;
}

.form-card {
  margin: 16px;
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.submit-btn {
  padding: 20px 16px 16px;
}

.duration-text {
  color: #1989fa;
  font-weight: 500;
}

.reason-label {
  color: #666;
  font-size: 13px;
  margin: 8px 0;
  line-height: 1.5;
}

.status-tag {
  margin-top: 6px;
}

.status-tag + button {
  margin-left: 8px; /* 新增样式规则 */
}

.history-card {
  margin: 16px;
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  :deep(.van-cell__value) {
    flex: none;
    width: 40%;
    text-align: right;
    color: #666;
  }
}

.van-picker__confirm {
  color: #1989fa;
}

.time-info span,
.status-info span,
.leave-off-info {
  display: block;
  margin-bottom: 4px;
}

.history-card :deep(.van-cell[status="3"]) {
  color: #999;
  background-color: #f2f2f2;
}

.cancelLeave {
  /* 去掉绝对定位，改为相对定位或其他合适布局方式 */
  position: relative;
  margin-left: 8px; /* 可根据实际调整距离 */
}

.create-time {
  color: #999;
  font-size: 12px;
}

.status-tag.approve-comment {
  margin-left: 5px;
  color: #999;
  font-size: 12px;
}

.remark-info span{
  display: block;
  margin-bottom: 4px;
}

.expense-info {
  display: flex;
  justify-content: flex-end; /* 内容靠右对齐 */
  align-items: center;
  flex-wrap: wrap; /* 防止内容过多溢出 */
}

.remark-info {
  margin-left: 8px; /* 报销主题与时间的间距 */
}
</style>